'use strict';

var draggable = require('vuedraggable');
require('yly-form-source/lib/yly-form-constants');
var cloneDeep = require('lodash/cloneDeep');

var script$2 = {
    name: 'YlyFormItemWrapper',
    functional: true,
    inject: [],
    props: {
        componentConfig: {
            type: Object,
            required: true
        },
        formSource: {
            type: Object,
            default: () => ({})
        },
        isSubComponent: {
            type: Boolean,
            default: false
        },
        renderScene: {
            type: String,
            required: true,
            validator: function (value) {
                var renderSceneList = ['ide', 'edit', 'read'];
                return renderSceneList.includes(value);
            }
        },
        parentWidget: {
            type: Object
        }
    },
    render: function (h, context) {
        var {componentConfig, formSource, renderScene, isSubComponent, parentWidget} = context.props;
        var calcComponentConfig = () => {
            if (!componentConfig.version || componentConfig.version !== 'v2.0') {
                formSource && formSource.formComponentsControl.constructor.convertOldComponentConfig(componentConfig);
            }
            return componentConfig;
        };
        var computedComponentConfig = calcComponentConfig();
        var clickItemWrapper = $event => {
            $event.stopPropagation();
            context.listeners.selectedItem && context.listeners.selectedItem(computedComponentConfig);
        };
        var handleChange = value => {
            context.parent.handleChange && context.parent.handleChange(value, calcComponentConfig.model);
        };
        var addItemInContainer = $event => {
            context.listeners.addItemInContainer && context.listeners.addItemInContainer($event);
        };
        var isRequired = computedComponentConfig.rules && computedComponentConfig.rules[0] && computedComponentConfig.rules[0].required;
        var getRenderCompName = () => {
            var originConfig = formSource.formComponentsControl.constructor.getComponentConfigByCode(computedComponentConfig.code);
            let renderCompName = originConfig.renderComponent[renderScene];
            return renderCompName;
        };
        var clickCopyAdd = $event => {
            $event.stopPropagation();
            $event.preventDefault();
            context.listeners.handleCopyComponent && context.listeners.handleCopyComponent(computedComponentConfig);
        };
        var clickDeleteOption = $event => {
            $event.stopPropagation();
            $event.preventDefault();
            context.listeners.deleteItem && context.listeners.deleteItem(computedComponentConfig.key);
        };
        var ideRenderOptions = h('div', {
            class: "form-item-options"
        }, [h('div', {
            class: "options-icon",
            on: {
                click: clickCopyAdd
            }
        }, [h('a-icon', {
            attrs: {
                type: "copy"
            }
        })]), h('div', {
            class: "options-icon",
            on: {
                click: clickDeleteOption
            }
        }, [h('a-icon', {
            attrs: {
                type: "delete"
            }
        })])]);
        var renderWrapperClass = () => {
            var ideClass = {
                'ide-display-component': computedComponentConfig.hidden,
                'select-form-item': computedComponentConfig.key === formSource.selectedComponent.key,
                'ide-item-wrapper': true,
                'hidden-comp': computedComponentConfig.hidden
            };
            var renderWrapperClass = {
                'form-item-wrapper': true,
                'is-required': isRequired
            };
            if (renderScene === 'ide') {
                Object.assign(renderWrapperClass, ideClass);
            }
            return renderWrapperClass;
        };
        var FormNodeStyle = () => {
            let width = componentConfig.width;
            if (isSubComponent) {
                width = parseFloat(100 / parentWidget.colNum) + '%';
            }
            if (typeof width === 'string' && (width.slice(-1) === '%' || width.slice(-2) === 'px')) {
                return {
                    width: width
                };
            }
            return {
                width: width ? parseFloat(width) + '%' : '100%'
            };
        };
        var isShowOptions = renderScene === 'ide' && computedComponentConfig.key === formSource.selectedComponent.key;
        var getRenderScene = () => {
            var emptyRenderOptions = '';
            var RenderSceneTemp = h('div', {
                style: {
                    display: computedComponentConfig.hidden && renderScene !== 'ide' ? 'none' : 'block',
                    ...FormNodeStyle()
                },
                class: renderWrapperClass(),
                on: {
                    click: clickItemWrapper
                },
                attrs: {
                    'data-type': computedComponentConfig.componentType,
                    'data-component-id': computedComponentConfig.key
                }
            }, [isShowOptions ? ideRenderOptions : emptyRenderOptions, h(getRenderCompName(), {
                props: {
                    key: computedComponentConfig.key,
                    record: computedComponentConfig,
                    componentConfig: computedComponentConfig,
                    renderScene: renderScene,
                    formSource: formSource
                },
                style: {},
                on: {
                    addItemInContainer: addItemInContainer,
                    change: handleChange
                }
            })]);
            return RenderSceneTemp;
        };
        return getRenderScene();
    }
};

function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
    if (typeof shadowMode !== 'boolean') {
        createInjectorSSR = createInjector;
        createInjector = shadowMode;
        shadowMode = false;
    }
    // Vue.extend constructor export interop.
    var options = typeof script === 'function' ? script.options : script;
    // render functions
    if (template && template.render) {
        options.render = template.render;
        options.staticRenderFns = template.staticRenderFns;
        options._compiled = true;
        // functional template
        if (isFunctionalTemplate) {
            options.functional = true;
        }
    }
    // scopedId
    if (scopeId) {
        options._scopeId = scopeId;
    }
    let hook;
    if (moduleIdentifier) {
        // server build
        hook = function (context) {
            // 2.3 injection
            context =
                context || // cached call
                    (this.$vnode && this.$vnode.ssrContext) || // stateful
                    (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional
            // 2.2 with runInNewContext: true
            if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
                context = __VUE_SSR_CONTEXT__;
            }
            // inject component styles
            if (style) {
                style.call(this, createInjectorSSR(context));
            }
            // register component module identifier for async chunk inference
            if (context && context._registeredComponents) {
                context._registeredComponents.add(moduleIdentifier);
            }
        };
        // used by ssr in case component is cached and beforeCreate
        // never gets called
        options._ssrRegister = hook;
    }
    else if (style) {
        hook = shadowMode
            ? function (context) {
                style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot));
            }
            : function (context) {
                style.call(this, createInjector(context));
            };
    }
    if (hook) {
        if (options.functional) {
            // register for functional component in vue file
            var originalRender = options.render;
            options.render = function renderWithStyleInjection(h, context) {
                hook.call(context);
                return originalRender(h, context);
            };
        }
        else {
            // inject component registration as beforeCreate hook
            var existing = options.beforeCreate;
            options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
        }
    }
    return script;
}

/* script */ var __vue_script__$2 = script$2;

/* template */

  /* style */
  var __vue_inject_styles__$2 = undefined;
  /* scoped */
  var __vue_scope_id__$2 = undefined;
  /* module identifier */
  var __vue_module_identifier__$2 = undefined;
  /* functional template */
  var __vue_is_functional_template__$2 = undefined;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  var __vue_component__$2 = /*#__PURE__*/normalizeComponent(
    {},
    __vue_inject_styles__$2,
    __vue_script__$2,
    __vue_scope_id__$2,
    __vue_is_functional_template__$2,
    __vue_module_identifier__$2,
    false,
    undefined,
    undefined,
    undefined
  );

var script$1 = {
    name: 'YlyFormItemContainer',
    components: {
        draggable,
        ylyFormItemWrapper: __vue_component__$2
    },
    props: {
        formSource: {
            type: Object,
            required: true
        },
        renderScene: {
            type: String,
            required: true
        },
        dragGroup: {
            type: Object,
            default: () => {
                return {
                    pull: function (to, from, item) {
                        if (to.options && to.options.group) {
                            return ['form-draggable', 'form-card', 'form-grid'].includes(to.options.group.name);
                        }
                        return false;
                    },
                    put: ['form-draggable', 'form-card', 'form-grid'],
                    name: 'form-draggable'
                };
            }
        },
        hideEmpty: {
            type: Boolean,
            default: false
        },
        parentChildKey: {
            type: String,
            default: () => 'children'
        },
        parentWidget: {
            type: Object
        },
        itemList: {
            type: Array,
            default() {
                return [];
            }
        }
    },
    data() {
        return {};
    },
    computed: {
        draggableOptions() {
            return {
                easing: 'cubic-bezier(1, 1, 1, 1)',
                animation: 200,
                fallbackOnBody: true,
                swapThreshold: 0.65,
                disabled: this.renderScene !== 'ide'
            };
        },
        isEmptyInIde() {
            return !this.hideEmpty && this.renderScene === 'ide' && this.formItemList.length === 0;
        },
        formItemList() {
            if (this.parentWidget) {
                return this.parentWidget[this.parentChildKey];
            } else {
                return this.itemList;
            }
        }
    },
    methods: {
        addItemInContainer($event) {
            console.log($event);
            if ($event.newIndex === 1 && this.formItemList.length === 1) {
                $event.newIndex = 0;
            }
            this.$emit('addItemInContainer', {
                formItemList: this.formItemList,
                parentWidget: this.parentWidget,
                widget: cloneDeep(this.formItemList[$event.newIndex]),
                $event: $event
            });
        },
        handleCopyComponent(widget) {
            this.formSource.formDataControl.copyItemInContainer({
                formItemList: this.formItemList,
                widget: cloneDeep(widget)
            });
        },
        updateItemInContainer($event) {
            console.log($event);
        },
        handleSelectItem(componentItem) {
            this.formSource.updateSelectedComponent(componentItem);
        },
        handleDeleteItem(key) {
            this.formSource.formDataControl.deleteItemInContainer({
                formItemList: this.formItemList,
                key
            });
        }
    }
};

/* script */ var __vue_script__$1 = script$1;
/* template */
var __vue_render__$1 = function() {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c(
    "div",
    { staticClass: "form-item-container" },
    [
      _c(
        "draggable",
        _vm._b(
          {
            staticClass: "draggable-box",
            class: {
              "form-item-list-empty": _vm.isEmptyInIde
            },
            attrs: {
              list: _vm.formItemList,
              group: _vm.dragGroup,
              ghostClass: "moving",
              filter: ".form-item-list-empty",
              tag: "div"
            },
            on: {
              add: function($event) {
                return _vm.addItemInContainer($event)
              },
              update: function($event) {
                return _vm.updateItemInContainer($event)
              }
            }
          },
          "draggable",
          _vm.draggableOptions,
          false
        ),
        [
          _vm.isEmptyInIde
            ? _c("div", { staticClass: "form-item-list-empty" }, [
                _vm._v("\n      请添加数据\n    ")
              ])
            : _vm._l(_vm.formItemList, function(componentConfig, index) {
                return _c(
                  "yly-form-item-wrapper",
                  _vm._g(
                    _vm._b(
                      {
                        key: componentConfig.key,
                        staticClass: "drag-move",
                        attrs: {
                          componentConfig: componentConfig,
                          parentWidget: _vm.parentWidget,
                          formSource: _vm.formSource,
                          renderScene: _vm.renderScene
                        },
                        on: {
                          selectedItem: _vm.handleSelectItem,
                          deleteItem: _vm.handleDeleteItem,
                          handleCopyComponent: _vm.handleCopyComponent
                        }
                      },
                      "yly-form-item-wrapper",
                      _vm.$attrs,
                      false
                    ),
                    _vm.$listeners
                  )
                )
              })
        ],
        2
      )
    ],
    1
  )
};
var __vue_staticRenderFns__$1 = [];
__vue_render__$1._withStripped = true;

  /* style */
  var __vue_inject_styles__$1 = undefined;
  /* scoped */
  var __vue_scope_id__$1 = undefined;
  /* module identifier */
  var __vue_module_identifier__$1 = undefined;
  /* functional template */
  var __vue_is_functional_template__$1 = false;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  var __vue_component__$1 = /*#__PURE__*/normalizeComponent(
    { render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 },
    __vue_inject_styles__$1,
    __vue_script__$1,
    __vue_scope_id__$1,
    __vue_is_functional_template__$1,
    __vue_module_identifier__$1,
    false,
    undefined,
    undefined,
    undefined
  );

var script = {
    name: 'YlyFormBuild',
    components: {
        YlyFormItemContainer: __vue_component__$1
    },
    props: {
        ideFormData: {
            type: Object,
            default() {
                return {};
            }
        },
        formSource: {
            type: Object,
            required: true
        }
    },
    computed: {
        formData() {
            return this.formSource.formDataControl && this.formSource.formDataControl.formData || ({});
        },
        formItemList: {
            get() {
                return this.formSource && this.formSource.formDataControl && this.formSource.formDataControl.formItemList;
            },
            set(val) {
                if (this.formSource && this.formSource.formDataControl) {
                    this.formSource.formDataControl.setFormList(val);
                }
            }
        },
        renderScene() {
            return this.formSource.sourceContent.renderScene;
        }
    },
    data() {
        return {};
    },
    created() {},
    methods: {
        addItemInContainer(content) {
            var {formItemList, widget, $event, parentWidget} = content;
            delete widget.editor;
            delete widget.mobileEditor;
            this.formSource.formDataControl.addItemInContainer({
                formItemList,
                widget,
                index: $event.newIndex,
                parentWidget,
                replace: true
            });
            this.ideFormData.list = formItemList;
        },
        getFormData() {
            return new Promise((resolve, reject) => {
                this.$refs.ylyForm.validate(async (err, values) => {
                    if (!err) {
                        return reject(err);
                    }
                    var CustomComponentFormData = await this.getCustomComponentFormData();
                    resolve({
                        ...this.formData,
                        CustomComponentFormData
                    });
                });
            });
        },
        async getCustomComponentFormData() {
            var customBusinessComponents = this.formSource.formComponentsControl.getCustomBusinessComponents();
            if (!customBusinessComponents || customBusinessComponents.size === 0) {
                return {};
            }
            var CustomComponentFormData = {};
            for (let [key, vNode] of customBusinessComponents) {
                CustomComponentFormData[key] = await vNode.getFormData();
            }
            return CustomComponentFormData;
        }
    }
};

/* script */ var __vue_script__ = script;
/* template */
var __vue_render__ = function() {
  var _vm = this;
  var _h = _vm.$createElement;
  var _c = _vm._self._c || _h;
  return _c(
    "div",
    { staticClass: "yly-form-build" },
    [
      _c(
        "a-form-model",
        {
          ref: "ylyForm",
          attrs: {
            layout: "horizontal",
            model: _vm.formData,
            hideRequiredMark: false
          }
        },
        [
          _c("yly-form-item-container", {
            ref: "YlyFormItemContainerRef",
            attrs: {
              itemList: _vm.formItemList,
              formSource: _vm.formSource,
              renderScene: _vm.renderScene
            },
            on: { addItemInContainer: _vm.addItemInContainer }
          })
        ],
        1
      )
    ],
    1
  )
};
var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;

  /* style */
  var __vue_inject_styles__ = undefined;
  /* scoped */
  var __vue_scope_id__ = undefined;
  /* module identifier */
  var __vue_module_identifier__ = undefined;
  /* functional template */
  var __vue_is_functional_template__ = false;
  /* style inject */
  
  /* style inject SSR */
  
  /* style inject shadow dom */
  

  
  var __vue_component__ = /*#__PURE__*/normalizeComponent(
    { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
    __vue_inject_styles__,
    __vue_script__,
    __vue_scope_id__,
    __vue_is_functional_template__,
    __vue_module_identifier__,
    false,
    undefined,
    undefined,
    undefined
  );

__vue_component__.install = function (vue) {
    vue.component(__vue_component__.name, __vue_component__);
};

module.exports = __vue_component__;
